package com.liu.controller;

import com.liu.controller.dto.PasswordDTO;
import com.liu.controller.dto.UserDTO;
import com.liu.entity.Admin;
import com.liu.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin")
//@CrossOrigin
@Slf4j
public class AdminController {

    private AdminService adminService;

    @Autowired
    @Qualifier("AdminServiceImpl")
    public void setAdminService(AdminService adminService){
        this.adminService = adminService;
    }


    /**
     * 登录
     * @param userDTO
     * @return
     */
    @PostMapping("/login")
    public Map<String, Object> loginUser(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        Map<String, Object> result = new HashMap<>();
        //登录验证
        log.info("登录的用户名:{} 登录的密码:{}", username, password);
        HashMap<String, Object> map = new HashMap<>();
        map.put("username",username);
        map.put("password",password);
        try {
            Admin adminDB = adminService.login(map);
            log.info("登录的用户:{}", adminDB.toString());
            result.put("success", true);
            result.put("data", adminDB);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("data", "用户名或密码错误!");
        }
        return result;
    }

    /**
     * 添加或更新
     *
     * @param admin
     */
    @PostMapping("/admin")
    public void addAdmin(@RequestBody Admin admin) {
        log.info("当前保存或修改管理员信息:{}", admin.toString());
        //根据传递过来的参数studentId是否存在来决定进入哪个方法
        if (admin.getId() != null && admin.getId().toString().length() > 0) {
            System.out.println(admin.getId());
            adminService.updateAdmin(admin);
        } else {
            System.out.println(admin.getId());
            adminService.addAdmin(admin);
        }
    }

    /**
     * 根据用户名查找
     * @param username
     * @return
     */
    @PostMapping("/findAdmin")
    public Admin findAdmin(String username){
        Admin admin = adminService.findAdmin(username);
        return admin;
    }

    /**
     * 修改密码
     * @param passwordDTO
     * @return
     */
    @PostMapping("/password")
    public int updatePwd(@RequestBody PasswordDTO passwordDTO){
        return adminService.updatePwd(passwordDTO);
    }

    /**
     * 根据id查找
     * @param id
     * @return
     */
    @GetMapping("/findById")
    public Admin admin(Integer id){
        return adminService.queryAdminById(id);
    }

    /*
    //测试
    @GetMapping("/list")
    public Admin queryAdminById(){
        Admin admin = adminService.queryAdminById(1);
        return admin;
    }*/
}
